// 优惠券数据存储 - 实现真正的数据联动
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

// 优惠券数据结构
export interface CouponForm {
  id: string
  name: string
  description: string
  type: string
  amount: number
  minAmount: number
  discountRate?: number
  maxDiscount?: number
  validType: string
  startTime?: string
  endTime?: string
  validDays?: number
  validMinutes?: number
  logistics?: string
  status: string
  usageDesc: string
  quantityType: string
  quantity: number
  grantType: string
  customerTags: string
  selectedTags: string[]
  userIds: string
  sites: string[]
  scope: string[]
  validDesc?: string
  selectedCategories?: (string | number)[]
  selectedBrands?: (string | number)[]
  showInCouponCenter?: boolean
  couponCenterSort?: number
  couponCenterStatus?: 'active' | 'inactive'
  createdAt: string
}

// 领券中心优惠券结构
export interface CouponCenterItem {
  id: number
  position: number
  couponId: string
  couponName: string
  couponType: string
  discount: string
  validPeriod: string
  applicableSites: string
  status: 'active' | 'inactive'
}

export const useCouponStore = defineStore('coupon', () => {
  // 优惠券管理页面的数据
  const couponList = ref<CouponForm[]>([
    {
      id: '1001',
      name: '新用户满减券',
      description: '新人专享',
      type: '满减券',
      amount: 20,
      minAmount: 100,
      validType: 'fixed',
      startTime: '2024-06-01',
      endTime: '2024-06-30',
      validDesc: '2024-06-01~2024-06-30',
      status: '发布',
      usageDesc: '新用户专享',
      quantityType: 'unlimited',
      quantity: 0,
      grantType: 'system',
      customerTags: '',
      selectedTags: [],
      userIds: '',
      sites: ['all'],
      scope: ['all'],
      selectedCategories: [],
      selectedBrands: [],
      showInCouponCenter: true,
      couponCenterSort: 1,
      couponCenterStatus: 'active',
      createdAt: '2024-06-01 10:00:00'
    },
    {
      id: '1002',
      name: '全场包邮券',
      description: '全场包邮',
      type: '包邮券',
      amount: 0,
      minAmount: 0,
      validType: 'today',
      validDays: 7,
      validDesc: '领券当日生效7天',
      logistics: 'ems',
      status: '作废',
      usageDesc: '',
      quantityType: 'limited',
      quantity: 100,
      grantType: 'targeted',
      customerTags: 'b_all',
      selectedTags: [],
      userIds: '',
      sites: ['all'],
      scope: ['all'],
      selectedCategories: [],
      selectedBrands: [],
      showInCouponCenter: false,
      couponCenterSort: 0,
      couponCenterStatus: 'inactive',
      createdAt: '2024-06-02 14:30:00'
    },
    {
      id: '1003',
      name: '夏日折扣券',
      description: '夏季特惠',
      type: '折扣券',
      amount: 0,
      minAmount: 50,
      discountRate: 8.8,
      maxDiscount: 30,
      validType: 'timed',
      validMinutes: 120,
      validDesc: '领取后120分钟',
      status: '发布',
      usageDesc: '',
      quantityType: 'unlimited',
      quantity: 0,
      grantType: 'system',
      customerTags: '',
      selectedTags: [],
      userIds: '',
      sites: ['mairo', 'yahoo_auction'],
      scope: ['category'],
      selectedCategories: [1, 11],
      selectedBrands: [],
      showInCouponCenter: true,
      couponCenterSort: 3,
      couponCenterStatus: 'active',
      createdAt: '2024-06-03 09:15:00'
    },
    {
      id: '1004',
      name: '无门槛券',
      description: '无门槛减',
      type: '无门槛券',
      amount: 10,
      minAmount: 0,
      validType: 'tomorrow',
      validDays: 3,
      validDesc: '次日生效3天',
      status: '草稿',
      usageDesc: '',
      quantityType: 'limited',
      quantity: 50,
      grantType: 'targeted',
      customerTags: 'users',
      selectedTags: [],
      userIds: 'user001\nuser002\nuser003',
      sites: ['all'],
      scope: ['brand'],
      selectedCategories: [],
      selectedBrands: [1, 2],
      showInCouponCenter: false,
      couponCenterSort: 0,
      couponCenterStatus: 'inactive',
      createdAt: '2024-06-04 16:45:00'
    }
  ])

  // 领券中心优惠券列表
  const couponCenterList = ref<CouponCenterItem[]>([
    {
      id: 1,
      position: 1,
      couponId: '1001',
      couponName: '新用户满减券',
      couponType: '满减券',
      discount: '满100减20',
      validPeriod: '2024-06-01~2024-06-30',
      applicableSites: '全站通用',
      status: 'active'
    },
    {
      id: 2,
      position: 2,
      couponId: '1003',
      couponName: '夏日折扣券',
      couponType: '折扣券',
      discount: '满50享8.8折，最高减30',
      validPeriod: '领取后120分钟',
      applicableSites: '煤炉、雅虎日拍',
      status: 'active'
    }
  ])

  // 获取所有优惠券（用于优惠券管理页面）
  const getAllCoupons = () => couponList.value

  // 同步优惠券管理页面的数据
  const syncCouponList = (newCouponList: CouponForm[]) => {
    couponList.value = [...newCouponList]
  }

  // 获取已发布的优惠券（用于领券中心）
  const getPublishedCoupons = computed(() => {
    return couponList.value.filter(coupon => coupon.status === '发布')
  })

  // 获取可添加到领券中心的优惠券（排除已添加的）
  const getAvailableCouponsForCenter = computed(() => {
    const addedCouponIds = couponCenterList.value.map(item => item.couponId)
    return couponList.value.filter(coupon =>
      coupon.status === '发布' && !addedCouponIds.includes(coupon.id)
    )
  })

  // 获取领券中心优惠券列表
  const getCouponCenterList = () => couponCenterList.value

  // 添加新优惠券（优惠券管理页面调用）
  const addCoupon = (coupon: Omit<CouponForm, 'id' | 'createdAt'>) => {
    const newId = (Math.max(...couponList.value.map(c => Number(c.id)), 1000) + 1).toString()
    const newCoupon: CouponForm = {
      ...coupon,
      id: newId,
      createdAt: new Date().toLocaleString('zh-CN')
    }
    couponList.value.unshift(newCoupon)
    return newCoupon
  }

  // 更新优惠券（优惠券管理页面调用）
  const updateCoupon = (id: string, updates: Partial<CouponForm>) => {
    const index = couponList.value.findIndex(c => c.id === id)
    if (index > -1) {
      couponList.value[index] = { ...couponList.value[index], ...updates }
      return couponList.value[index]
    }
    return null
  }

  // 删除优惠券（优惠券管理页面调用）
  const deleteCoupon = (id: string) => {
    const index = couponList.value.findIndex(c => c.id === id)
    if (index > -1) {
      couponList.value.splice(index, 1)
      // 同时从领券中心移除
      const centerIndex = couponCenterList.value.findIndex(c => c.couponId === id)
      if (centerIndex > -1) {
        couponCenterList.value.splice(centerIndex, 1)
      }
      return true
    }
    return false
  }

  // 发布优惠券（优惠券管理页面调用）
  const publishCoupon = (id: string) => {
    return updateCoupon(id, { status: '发布' })
  }

  // 作废优惠券（优惠券管理页面调用）
  const cancelCoupon = (id: string) => {
    return updateCoupon(id, { status: '作废' })
  }

  // 添加优惠券到领券中心（领券中心页面调用）
  const addToCouponCenter = (couponId: string, position: number) => {
    const coupon = couponList.value.find(c => c.id === couponId)
    if (!coupon) return null

    // 检查位置是否被占用
    const existingPosition = couponCenterList.value.find(c => c.position === position)
    if (existingPosition) {
      throw new Error(`位置 ${position} 已被占用`)
    }

    // 生成优惠内容描述
    let discount = ''
    if (coupon.type === '满减券') {
      discount = `满${coupon.minAmount}减${coupon.amount}`
    } else if (coupon.type === '折扣券') {
      discount = `满${coupon.minAmount}享${coupon.discountRate}折`
      if (coupon.maxDiscount) {
        discount += `，最高减${coupon.maxDiscount}`
      }
    } else if (coupon.type === '包邮券') {
      discount = `免运费(${getLogisticsName(coupon.logistics || 'ems')})`
    } else if (coupon.type === '无门槛券') {
      discount = `无门槛减${coupon.amount}`
    }

    // 获取适用站点描述
    const applicableSites = getSitesDescription(coupon.sites)

    const newId = Math.max(...couponCenterList.value.map(c => c.id), 0) + 1
    const newItem: CouponCenterItem = {
      id: newId,
      position,
      couponId: coupon.id,
      couponName: coupon.name,
      couponType: coupon.type,
      discount,
      validPeriod: coupon.validDesc || '',
      applicableSites,
      status: 'active'
    }

    couponCenterList.value.push(newItem)
    return newItem
  }

  // 从领券中心移除优惠券
  const removeFromCouponCenter = (id: number) => {
    const index = couponCenterList.value.findIndex(c => c.id === id)
    if (index > -1) {
      couponCenterList.value.splice(index, 1)
      return true
    }
    return false
  }

  // 更新领券中心优惠券状态
  const updateCouponCenterStatus = (id: number, status: 'active' | 'inactive') => {
    const item = couponCenterList.value.find(c => c.id === id)
    if (item) {
      item.status = status
      return true
    }
    return false
  }

  // 获取物流方式名称
  function getLogisticsName(logistics: string): string {
    const logisticsMap: Record<string, string> = {
      'ems': '日本邮政EMS',
      'sal': 'DHL',
      'air': '航空',
      'sea': '海运'
    }
    return logisticsMap[logistics] || logistics
  }

  // 获取适用站点描述
  function getSitesDescription(sites: string[]): string {
    if (sites.includes('all')) {
      return '全站通用'
    }

    const siteMap: Record<string, string> = {
      'mairo': '煤炉',
      'yahoo_auction': '雅虎日拍',
      'yahoo_fleamarket': '雅虎闲置',
      'bookoff': 'bookoff'
    }

    return sites.map(site => siteMap[site] || site).join('、')
  }

  return {
    // 数据
    couponList,
    couponCenterList,

    // 优惠券管理页面方法
    getAllCoupons,
    syncCouponList,
    addCoupon,
    updateCoupon,
    deleteCoupon,
    publishCoupon,
    cancelCoupon,

    // 领券中心页面方法
    getPublishedCoupons,
    getAvailableCouponsForCenter,
    getCouponCenterList,
    addToCouponCenter,
    removeFromCouponCenter,
    updateCouponCenterStatus,

    // 工具方法
    getLogisticsName,
    getSitesDescription
  }
})
